package org.zxl.iotest.netty.protobuf.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class TcpProtobufClient {
    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 54300;

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            // 启动客户端.
            ChannelFuture f = b.connect(host, port).sync();


            TcpClientService clientService = new TcpClientService();
            String messageType = "";
            Scanner sc = new Scanner(System.in);
            while (!"exit".equals(messageType)){
                log.info("消息类型-1：心跳，2:公共信息，请输入");
                messageType = sc.nextLine();
                //ChannelFuture cf2 = b.connect("127.0.0.1", 8764).sync();  //可以使用多个端口
                //发送消息, Buffer类型. write需要flush才发送, 可用writeFlush代替
                //cf1.channel().writeAndFlush(Unpooled.copiedBuffer(message.getBytes()));
//            cf1.channel().writeAndFlush(Unpooled.copiedBuffer("666".getBytes()));
//        Thread.sleep(2000);
//        cf1.channel().writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));
                //cf2.channel().writeAndFlush(Unpooled.copiedBuffer("999".getBytes()));
                if("1".equals(messageType)){
                    clientService.sendHeartbeat(f.channel());
                }
                else if("2".equals(messageType)){
                    clientService.sendCommon(f.channel());
                }else {
                    clientService.sendCommon(f.channel());
                }
            }


            f.channel().closeFuture().sync();
            group.shutdownGracefully();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}
